package com.mew.lobby.handler.sms;

import cn.hutool.core.util.RandomUtil;
import com.mew.common.config.ConstantValue;
import com.mew.common.config.RedisConstantValue;
import com.mew.common.dc.redis.UserProfileRedisService;
import com.mew.common.entity.user.User;
import com.mew.common.exception.ResponseCode;
import com.mew.common.rest.LongMessage;
import com.mew.common.rest.StringMessage;
import com.mew.common.rest.bo.MewSession;
import com.mew.common.util.SmsSDKUtil;
import com.mew.lobby.annotation.LobbyHandler;
import com.mew.lobby.config.MewGameConfig;
import com.mew.lobby.net.LobbyHandlerMapCmdType;
import com.mew.lobby.net.MewHandler;
import com.zebra.remoting.protocol.ZebraCommand;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.concurrent.TimeUnit;


@Service
@Slf4j
@LobbyHandler(LobbyHandlerMapCmdType.SMS)
public class SMSHandler implements MewHandler<StringMessage> {

    @Autowired
    private MewGameConfig smsConfig;

    @Autowired
    private RedisTemplate<String,Object> redisTemplate;

    @Autowired
    private UserProfileRedisService userProfileRedisService;

    @Override
    public void handle(ZebraCommand<StringMessage> zebraCommand, MewSession session) {
        LongMessage build = LongMessage.builder().l(5*60).build();
        StringMessage message = zebraCommand.getRequest();
        String telNumber = message.getS();

        //绑没绑手机
        User user = userProfileRedisService.getRedisUserById(zebraCommand.getUserId());

        if (StringUtils.isNotEmpty(user.getTelNumber()) && !user.getTelNumber().equals(telNumber)){
            //绑了 不一样
            zebraCommand.sendFailureCode(ResponseCode.NoTUserTel.code());
            return;
        }

        //发过还没用
        String value = (String) redisTemplate.opsForValue().get(RedisConstantValue.USER_SMS + telNumber);
        if (StringUtils.isNotEmpty(value)){
            Long expire = redisTemplate.getExpire(RedisConstantValue.USER_SMS + telNumber, TimeUnit.SECONDS);
            build.setL(expire);
            zebraCommand.sendMessage(build);
            return;
        }

        //发送
        String rand = RandomUtil.randomInt(1000, 9999)+"";
        boolean sms = SmsSDKUtil.sendSMS(telNumber, rand, 5, smsConfig.getUrl(), smsConfig.getApikey());

        log.info("xxxxxxxxxx SMSHandler 手机号：{} 验证码：{} 发送情况：{}",telNumber,rand,sms);

        if (sms){
            //成功
            redisTemplate.opsForValue().set(RedisConstantValue.USER_SMS+telNumber,rand, ConstantValue.AUTH_TEL_TIME, TimeUnit.MINUTES);
            zebraCommand.sendMessage(build);
        }else {
            zebraCommand.sendFailureCode(ResponseCode.SMSFail.code());
        }

    }

}
